package com.mrsltec.chat.service;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import com.mrsltec.chat.MainActivity;
import com.mrsltec.chat.R;

import org.json.JSONException;
import org.json.JSONObject;

import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketConnectionHandler;
import de.tavendo.autobahn.WebSocketException;

public class WebSocketClientService extends Service {
    private final String TAG = "SosWebSocketClientService";
    final WebSocketConnection mConnection = new WebSocketConnection();
    private final IBinder mBinder = new WebSocketClientBinder();
    NotificationManager mNM;
    private static final String TAGE = "zmr-1234567";
    static int NOTIFY_ID = 1000;
    String wsuri = "ws://163t682w40.51mypc.cn:29409/socket.io/";

    public WebSocketClientService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return mBinder;
    }

    @Override
    public void onCreate() {
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        initWebSocket();
        super.onCreate();
        Log.e(TAGE, "Service Create");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    /**
     * 销毁
     */
    @Override
    public void onDestroy() {
        if (mConnection.isConnected()) {
            mConnection.disconnect();
        }
        super.onDestroy();
        Log.e(TAGE, "Service Destroy");
    }

    private void initWebSocket() {
        try {
            mConnection.connect(wsuri, new WebSocketConnectionHandler() {
                @Override
                public void onOpen() {
                    Log.e(TAGE, "Status: Connected to " + wsuri);
                }

                @Override
                public void onTextMessage(String payload) {
                    //接受服务器消息
                    Log.e(TAGE, "Status: Over msg" + payload);
                    try {
                        JSONObject jsonObject = new JSONObject(payload);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        initWebSocket();
                        //Toast.makeText(BaseActivity.activity,"服务器已经重连！",Toast.LENGTH_LONG).show();
                        // restartApplication();
                    }
                }

                @Override
                public void onClose(int code, String reason) {
                    //关闭服务器链接
                    Log.e(TAGE, "Status: Connection lost" + reason);
                    //Toast.makeText(BaseActivity.activity,"Connection lost="+reason,Toast.LENGTH_LONG).show();
                    //restartApplication();
                    initWebSocket();
                    //Toast.makeText(MainActivity.,"服务器已经重连！", Toast.LENGTH_LONG).show();
                }
            });

        } catch (WebSocketException e) {
            Log.e(TAGE, e.toString());
            //restartApplication();
            initWebSocket();
        }
    }


    private void restartApplication() {
        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }


    public class WebSocketClientBinder extends Binder {
        public WebSocketClientService getService() {
            return WebSocketClientService.this;
        }

        public void sendXxx(String addr) {
            if (mConnection.isConnected())
                mConnection.sendTextMessage(addr);

        }
    }

    /***
     * 发送通知
     *
     * @param context
     * @param title
     * @param contentText
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public static void sendNotification(Context context, String title, String contentText) {
        NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Intent resultIntent = new Intent(context, MainActivity.class);//MainActivity  GetMesgActivity
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pi = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification notification = new Notification.Builder(context)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setTicker("点击查看消息")
                .setContentTitle(title)
                .setContentText(contentText)
                .setContentIntent(pi)
                .setDefaults(Notification.DEFAULT_ALL)//DEFAULT_VIBRATE
                .build();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notifyMgr.notify(NOTIFY_ID, notification);
    }
}
